<?php

namespace app\api\controller;

use think\facade\Db;
use think\facade\Log;
use think\facade\Validate;
use think\facade\Filesystem;
use think\facade\Request;
use xhadmin\db\Customer as CustomerDb;
use xhadmin\db\Introducer as IntroducerDb;
use xhadmin\service\admin\record\CustomerService;
use xhadmin\service\admin\record\IntroducerService;
use function GuzzleHttp\Psr7\str;


class Customer extends Base
{
    public function index(){
        //echo 'user';
        $limit  = $this->request->post('limit', 10, 'intval');
        $data['limit'] = $limit;
        $offset = $this->request->post('offset', 0, 'intval');
        $page   = floor($offset / $limit) +1 ;
        $name = $this->request->param('name', '', 'strip_tags,trim');
        if(!empty($name)){
            $where['first_name|last_name|id_card'] = ['like','%'.$name.'%'];
        }
        //p($this->userInfo['user_id']);exit;
        $where['create_by'] = ['=',$this->userInfo['user_id']];
        $where['status'] = ['=',0];
        $limit = ($page-1) * $limit.','.$limit;
        try{
            $res = CustomerService::pageList(formatWhere($where),$limit,'*',$orderby = '');
            foreach ($res['list'] as $key=>&$val) {
                $val['work_year_month'] = $val['work_year'].'年'.$val['work_month'].'个月';
                $val['name'] = $val['first_name'].'</br> '.$val['last_name'];
            }
            $list = $res['list'];
        }catch(\Exception $e){
            exit($e->getMessage());
        }
        $data['status'] = '00';
        $data['rows']  = $list;
        $data['total'] = $res['count'];
        $data['offset'] = $offset;
        return json($data);
    }

    public function add(){
        $postField = 'status,id_card,idcardimg,idcardimgel,bankimg,wjbhzimg,first_name,last_name,birth_day,
			religion,addr,expiry_date,id_card_upside_no,id_card_upside_two,work_year,work_month,mobile,director,is_rename,is_hz_dg,
			is_yhb_dg,is_introducer,introducer,introducer_id,director_id,is_jlzdg,qkd_info,work_times';
        $data = $this->request->only(explode(',',$postField),'post');
        $data['director_id'] = $this->userInfo['user_id'];
        $data['create_by'] = $this->userInfo['user_id'];
        if(empty($data['id_card'])) {
            return json(['status'=>'01','msg'=>'信息确少']);
        }
        $is_idcard = CustomerDb::countList(['id_card'=>$data['id_card']]);
        if($is_idcard) {
            return json(['status'=>'01','msg'=>'该客户已经存在']);
        }
        if((!isset($data['introducer_id']) || empty($data['introducer_id'])) && $data['is_introducer']==1){
            //表示新增介绍人
            $is_ex = IntroducerDb::countList(['name'=>$data['introducer']]);
            if($is_ex) {
                return json(['status'=>'01','msg'=>'该介绍人已经存在']);
            }
            try {
                $data['introducer_id'] = IntroducerService::add(['name'=>$data['introducer']]);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        try {
            $now = time();
            $insert_id = CustomerService::add($data);
            $dataLog['c_id'] = $insert_id;
            $dataLog['id_card'] = $data['id_card'];
            $dataLog['status'] = 0;
            $dataLog['create_by'] = $this->userInfo['user_id'];
            $dataLog['create_time'] = $now;
            Db::name("customer_log")->insert($dataLog);
        } catch (\Exception $e) {
            $this->error($e->getMessage());

        }
        return json(['status'=>'00','msg'=>'添加成功']);
    }


    public function detail(){
        $id = $this->request->post('id', '', 'strip_tags,trim');
        if(!empty($no)) {
            $row = CustomerDb::getInfo($id);

        } else {
            $row = [];
        }
        $this->returnMsg(200,'ok',$row);
    }

    public function update() {
        $postField = 'id,status,id_card,idcardimg,idcardimgel,bankimg,wjbhzimg,first_name,last_name,birth_day,
			religion,addr,expiry_date,id_card_upside_no,id_card_upside_two,work_year,work_month,mobile,director,is_rename,is_hz_dg,
			is_yhb_dg,is_introducer,introducer,introducer_id,director_id,is_jlzdg,qkd_info,work_times';
        $data = $this->request->only(explode(',',$postField),'post');
        //p($data);exit;
        if(empty($data['id'])) {
            return json(['status'=>'01','msg'=>'信息确少']);
        }
        if((!isset($data['introducer_id']) || empty($data['introducer_id'])) && $data['is_introducer']==1){
            //表示新增介绍人
            $is_ex = IntroducerDb::countList(['name'=>$data['introducer']]);
            if($is_ex) {
                return json(['status'=>'01','msg'=>'该介绍人已经存在']);
            }
            try {
                $data['introducer_id'] = IntroducerService::add(['name'=>$data['introducer']]);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        try {
            CustomerService::update($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return json(['status'=>'00','msg'=>'修改成功']);
    }



    private function upload($filekey){
        $file = $this->request->file($filekey);
        try{
            if(!config('xhadmin.file_size')){
                $file_sieze = 50 * 1024 * 1024;
            }else{
                $file_sieze = config('xhadmin.file_size') * 1024 * 1024;
            }

            if(!config('xhadmin.file_type')){
                $file_type = 'gif,png,jpg,jpeg,doc,docx,csv,pdf,rar,zip,txt,mp4,flv';
            }else{
                $file_type = config('xhadmin.file_type');
            }

            if(!Validate::fileExt($file,$file_type) || !Validate::fileSize($file,$file_sieze)){
                throw new \Exception('上传验证失败');
            }

            if(config('my.oss_status')){
                $url = \utils\oss\OssService::OssUpload(['tmp_name'=>$file->getPathname(),'extension'=>$file->extension()]);
                $url = rtrim(ltrim(config('my.upload_dir'),'.'),'/') . '/' . ltrim($url,'/');
            }else{
                $info = Filesystem::disk('public')->putFile(\utils\oss\OssService::setFilepath(),$file,'uniqid');
                $url = \utils\oss\OssService::getAdminFileName(basename($info));
            }
        }catch(\Exception $e){
            log::error('图片上传错误：'.print_r($e->getMessage(),true));
            throw new \Exception($e->getMessage());
        }
        return $url;
    }


    //普通图片上传
    public function uploadImages()
    {
        $url = $this->upload('file');
        if($url){
            return json(['status'=>00,'data'=>$url]);
        }else{
            return json(['status'=>01,'msg'=>'上传失败']);
        }
    }

    public function checkIdCard(){
        $id_card=$this->request->param('id_card', '', 'strip_tags,trim');
        $ret = CustomerDb::countList(['id_card'=>$id_card]);
        if($ret) {
            return json(['status'=>'01','msg'=>'该客户已经存在']);
        }
        return json(['status'=>'00','msg'=>'']);
    }



}
